package controller

import (
	"gitee.com/kordar/goadmin/admin/enums"
	admin "gitee.com/kordar/goadmin/admin/form"
	"gitee.com/kordar/goadmin/admin/repository"
	"gitee.com/kordar/goadmin/admin/util"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	util2 "github.com/kordar/ginsys/util"
	"github.com/kordar/gocfg"
	response "github.com/kordar/goframework_resp"
	jwt2 "github.com/kordar/gojwt"
	"github.com/mojocn/base64Captcha"
	"strconv"
)

type AuthController struct {
	captcha *base64Captcha.Captcha
	repos   *repository.AdminRepository
}

func NewAuthController(captcha *base64Captcha.Captcha, repos *repository.AdminRepository) *AuthController {
	return &AuthController{captcha: captcha, repos: repos}
}

// Captcha 图形验证码
func (c AuthController) Captcha(ctx *gin.Context) {
	id, b64s, _, _ := c.captcha.Generate()
	response.Success(ctx, "success", map[string]interface{}{
		"token": id, "base64": b64s,
	})
}

// Login 登录系统
func (c AuthController) Login(ctx *gin.Context) {
	f := admin.LoginForm{}
	if err := util2.DefaultGetValidParams(ctx, &f); err != nil {
		response.Error(ctx, err, nil)
		return
	}

	if verify := c.captcha.Verify(f.Token, f.Code, true); !verify {
		response.Error(ctx, "verification code error", nil)
		return
	}

	sysAdmin, err := c.repos.Login(f.Username, f.Password)
	if err != nil {
		response.Error(ctx, err, nil)
		return
	}

	claims := jwt.MapClaims{}
	claims["id"] = strconv.FormatInt(sysAdmin.ID, 10)
	response.Success(ctx, "", map[string]interface{}{
		"token": jwt2.GenToken(claims, enums.HmacSampleSecret),
		"user": map[string]interface{}{
			"id":       sysAdmin.ID,
			"phone":    sysAdmin.Phone,
			"username": sysAdmin.Username,
			"avatar":   util.DomainImage(sysAdmin.Avatar),
			"type":     sysAdmin.Type,
		},
	})

}

// Config 登录配置
func (c AuthController) Config(ctx *gin.Context) {
	section := gocfg.Get("goadmin.login")
	response.Success(ctx, "success", section)
}
